package com.dhcc.demo.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dhcc.cdc.busi.entity.CdcDictionaryEntity;
import com.dhcc.cdc.busi.entity.CdcExaminateEntity;
import com.dhcc.cdc.busi.service.ICdcDictionaryService;
import com.dhcc.cdc.busi.service.ICdcExaminationService;
import com.dhcc.cdc.sys.entity.CdcDataEntity;
import com.dhcc.cdc.sys.service.ICdcDataService;
import com.dhcc.core.api.controller.BaseApiController;
import com.dhcc.core.components.httpClient.utils.JSON;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.sdc.base.entity.ContraindicationEntity;
import com.dhcc.sdc.base.entity.SdcBaseAssessmentEntity;
import com.dhcc.sdc.base.service.IContraindicationService;
import com.dhcc.sdc.base.service.ISdcBaseAssessmentService;
import com.dhcc.sdc.base.service.impl.SdcBaseAssessmentServiceImpl;
import com.dhcc.sdc.busi.entity.SdcBusiContraindicationEntity;
import com.dhcc.sdc.busi.entity.SdcBusiEvaluationEntity;
import com.dhcc.sdc.busi.entity.SdcBusiEvaluationHisEntity;
import com.dhcc.sdc.busi.entity.SdcBusiQcTriggeredEntity;
import com.dhcc.sdc.busi.service.ISdcBusiContraindicationService;
import com.dhcc.sdc.busi.service.ISdcBusiEvaluationHisService;
import com.dhcc.sdc.busi.service.ISdcBusiEvaluationService;
import com.dhcc.sdc.busi.service.ISdcBusiQcTriggeredService;
import io.swagger.annotations.*;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedCaseInsensitiveMap;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * API过程质控接口
 * 
 * @ClassName: ApiReceiveDataController
 * @Description: TODO
 * @author: zx
 * @date: 2023年06月02日 上午10:04:55
 */
@RestController
@RequestMapping("${sys.apiPath}")
@Api("过程质控接口")
public class ProcessQuilityController extends BaseApiController {
    @Autowired
    private ISdcBusiQcTriggeredService sdcBusiQcTriggeredService;
    @Autowired
    private ISdcBusiEvaluationService sdcBusiEvaluationService;
    @Autowired
    private ISdcBaseAssessmentService sdcBaseAssessmentService;
    @Autowired
    private ISdcBusiContraindicationService sdcBusiContraindicationService;
    @Autowired
    private IContraindicationService contraindicationService;
    /**
     * 质控项是否触发接口
     */
    @GetMapping("quilityIsTrigger")
    @ApiOperation(value = "质控项是否触发接口")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "episodeId", value = "就诊号", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "qcId", value = "质控项ID", required = true)})
    @ResponseBody
    public R quilityIsTrigger(@RequestParam(required = true)  String episodeId,@RequestParam(required = true)  String qcId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("episodeId",episodeId);
        map.put("qcId",qcId);
        List<SdcBusiQcTriggeredEntity> res = sdcBusiQcTriggeredService.list(map);
        if(CommonUtil.isNotEmpty(res) && res.size()>0){
            return R.ok("triggered");
        }else{
            return R.ok("notTriggered");
        }
    }
    /**
     * 获取评估分值
     */
    @GetMapping("getEvalScore")
    @ApiOperation(value = "获取评估分值",notes="按评估时间正序返回")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "episodeId", value = "就诊号", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "evalCode", value = "评估表代码", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "startDate", value = "开始时间(yyyy-MM-dd HH:mm:ss)", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "endDate", value = "结束时间(yyyy-MM-dd HH:mm:ss)", required = false)})
    @ResponseBody
    public R getEvalScore(@RequestParam(required = true)  String episodeId,@RequestParam(required = true)  String evalCode,@RequestParam(required = false)  String startDate,@RequestParam(required = false)  String endDate) {
        if(CommonUtil.isEmpty(episodeId)){
            return R.error("就诊号不允许为空！");
        }
        if(CommonUtil.isEmpty(evalCode)){
            return R.error("评估表代码不允许为空！");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code",evalCode);
        List<SdcBaseAssessmentEntity> asse = sdcBaseAssessmentService.list(map);
        if(CommonUtil.isNotEmpty(asse) && asse.size()>0){
            map.clear();
            map.put("episodeId",episodeId);
            map.put("assessmentId",asse.get(0).getId());
            map.put("startDate",startDate);
            map.put("endDate",endDate);
            List<SdcBusiEvaluationEntity> res = sdcBusiEvaluationService.list(map);
            if(CommonUtil.isNotEmpty(res) && res.size()>0){
                Map resList = new LinkedCaseInsensitiveMap();
                JSONObject json = new JSONObject(new LinkedHashMap());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                for(int i=0;i<res.size();i++){
                    resList.put(res.get(i).getCreateDate() == null?"":sdf.format(res.get(i).getCreateDate()),res.get(i).getScore());
                    json.put(res.get(i).getCreateDate() == null?"":sdf.format(res.get(i).getCreateDate()),res.get(i).getScore());
                }
                return R.ok().put("evalInfo",resList);
            }else{
                return R.error("当前就诊患者无该评估表的评估记录。");
            }
        }else{
            return R.error("不存在code为"+evalCode+"的评估表。");
        }


    }

    /**
     * 病历回写接口
     */
    @GetMapping("EMRBack")
    @ApiOperation(value = "病历回写接口（评估、禁忌）",notes="评估支持按照时间段获取，禁忌获取全部已审核的禁忌")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "episodeId", value = "就诊号", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "type", value = "类型（0：全部 1：评估 2：禁忌）", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "startTime", value = "开始时间(yyyy-MM-dd)，非必填", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "endTime", value = "结束时间(yyyy-MM-dd)，非必填", required = false)})
    @ResponseBody
    public R EMRBack(@RequestParam(required = true)  String episodeId,@RequestParam(required = true)  String type,@RequestParam(required = false)  String startTime,@RequestParam(required = false)  String endTime) {
        if(CommonUtil.isEmpty(episodeId)){
            return R.error("就诊号不能为空！");
        }
        if(CommonUtil.isEmpty(type)){
            return R.error("类型不能为空！");
        }
        if(!"0".equals(type)&&!"1".equals(type)&&!"2".equals(type)){
            return R.error("类型只能传入0、1、2！");
        }

        List<String> evalLis = new ArrayList<String>();//评估
        StringBuffer ctdStr = new StringBuffer();//禁忌
        Map<String, Object> map = new HashMap<String, Object>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //评估
        if("1".equals(type)||"0".equals(type)){
            map.put("episodeId",episodeId);
            map.put("startTime",startTime);
            map.put("endTime",endTime);
            List<SdcBusiEvaluationEntity> evalList = sdcBusiEvaluationService.list(map);
            if(CommonUtil.isNotEmpty(evalList)){
                for(int i=0;i<evalList.size();i++){
                    StringBuffer evalItem=new StringBuffer();
                    map.clear();
                    map.put("asId",evalList.get(i).getAssessmentId());
                    List<SdcBaseAssessmentEntity> eDic = sdcBaseAssessmentService.list(map);
                    evalItem.append(sdf.format(evalList.get(i).getUpdateDate())+"行");
                    if(CommonUtil.isNotEmpty(eDic)&& eDic.size()>0){
                        evalItem.append(eDic.get(0).getDescription()+"，");
                    }
                    evalItem.append("分值："+evalList.get(i).getScore()+"，");
                    if(CommonUtil.isNotEmpty(evalList.get(i).getLevel())){
                        evalItem.append("评估结果："+evalList.get(i).getLevel()+"，");
                    }
                    if(CommonUtil.isNotEmpty(evalList.get(i).getUpdateName())) {
                        evalItem.append("评估人：" + evalList.get(i).getUpdateName());
                    }
                    // evalStr.append("节点："+evalList.get(i).getNodeId()+",");
                    evalLis.add(evalItem.toString());
                }
            }
        }
        //禁忌
        if("2".equals(type)||"0".equals(type)){
            map.clear();
            map.put("episodeId",episodeId);
//            map.put("startTime",startTime);
//            map.put("endTime",endTime);
            List<SdcBusiContraindicationEntity> ctdList =  sdcBusiContraindicationService.manuallist(map);
            if(CommonUtil.isNotEmpty(ctdList)){
                for (int i=0;i<ctdList.size();i++){
                    if(ctdList.get(i).getResult() == 1){
                        if(i==0){
                            ctdStr.append("患者有");
                        }
                        map.clear();
                        map.put("ciId",ctdList.get(i).getContraindicationId());
                        List<ContraindicationEntity> ciDic = contraindicationService.list(map);
                        if(CommonUtil.isNotEmpty(ciDic) && ciDic.size()>0){
                            ctdStr.append(ciDic.get(0).getName());
                        }
                        if(i!= ctdList.size()-1){
                            ctdStr.append("、");
                        }
                    }
                }
            }
        }
        return R.ok().put("evalInfo",evalLis).put("assessmentInfo",ctdStr.toString());
    }
}
